﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using STSdb.General.Collections;
using STSdb.General.Buffers;

namespace STSdb.Persist
{
    public class SerializableIndexerPersist<T> : IIndexerPersist<T>
    {
        //Debug.Assert(typeof(T).IsSerializable);
        
        public void Store(BinaryWriter writer, IIndexer<T> values)
        {
            byte[] buffer = new byte[(int)Math.Ceiling(values.Count / 8.0)];

            object[] array = new object[values.Count];
            int length = 0;

            for (int i = 0; i < values.Count; i++)
            {
                object value = values[i];
                if (value != null)
                {
                    buffer.SetBit(i, 1);
                    array[length++] = value;
                }
                //else
                //    buffer.SetBit(i, 0);
            }

            writer.Write(buffer);

            BinaryFormatter formatter = new BinaryFormatter();
            for (int i = 0; i < length; i++)
                formatter.Serialize(writer.BaseStream, array[i]);
        }

        public void Load(BinaryReader reader, IIndexer<T> values)
        {
            byte[] buffer = reader.ReadBytes((int)Math.Ceiling(values.Count / 8.0));

            BinaryFormatter formatter = new BinaryFormatter();
            for (int i = 0; i < values.Count; i++)
                values[i] = (T)(buffer.GetBit(i) == 1 ? formatter.Deserialize(reader.BaseStream) : null);            
        }
    }
}
